<template>
  <div class="app-container">

    <div class="search-div">
      <el-form label-width="70px" size="small">
        <el-row>
          <el-col :span="8">
            <el-form-item label="关 键 字">
              <el-input style="width: 95%" v-model="searchObj.keyword" placeholder="样本编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="操作时间">
              <el-date-picker
                v-model="createTimes"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="margin-right: 10px;width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="display:flex">
          <el-button type="primary" icon="el-icon-search" size="mini" :loading="loading" @click="searchData()">搜索</el-button>
          
          <el-button type="danger" v-if="$hasPermission('product:protr:delete')" class="btn-add" size="mini" @click="batchRemove()" >批量删除</el-button>
          <el-button type="info" v-if="$hasPermission('product:protr:export')" size="mini" :loading="loading" @click="exportHandle()">导出</el-button>
        </el-row>
      </el-form>
    </div>
    <br />
    <el-upload v-if="$hasPermission('product:protr:upload')"
      class="upload-demo"
      ref="upload"
      :action="uploadUrl"
      :headers="headerData"
      :on-success="uploadSuccess"
      :on-error="uploadFaild"
      :auto-upload="false"
      :limit="1"
      :on-exceed="handleExceed"
      style="width: 300px;"
      :file-list="fileList"
	  :on-change="handleChange">

      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传该文件</el-button>
      <div slot="tip" class="el-upload__tip">只能上传xls/xlsx文件</div>
    </el-upload>


    <!-- 列表 -->
    <el-table

      v-loading="listLoading"
      :data="list"
      stripe
      border
      style="width: 100%;margin-top: 10px;"
      @selection-change="handleSelectionChange">

      <el-table-column type="selection"/>
      <el-table-column
        label="序号"
        width="70"
        align="center">
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column prop="sampleNo" label="样本编号" align="center"  />
      <el-table-column prop="trValue" label="TR数值" align="center" />
      <el-table-column prop="createDate" label="创建时间" align="center" />

      <el-table-column label="操作" width="80" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button v-if="$hasPermission('product:protr:delete')" type="danger" icon="el-icon-delete" size="mini" @click="removeDataById(scope.row.id)" title="删除" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      :current-page="page"
      :total="total"
      :page-size="limit"
      :page-sizes="[5, 10, 20, 30, 40, 50, 100]"
      style="padding: 30px 0; text-align: center;"
      layout="sizes, prev, pager, next, jumper, ->, total, slot"
      @current-change="fetchData"
      @size-change="changeSize"
    />

    <!-- <div class="tools-div">

    </div> -->


    <el-dialog title="以下数据已存在,继续上传则会覆盖,是否继续?" :visible.sync="reDataDialogVisible" width="70%" >

      <el-table


        :data="reTrs"
        stripe
        border
        style="width: 100%;margin-top: 10px;">

        <el-table-column
          label="序号"
          width="70"
          align="center">
          <template slot-scope="scope">
            {{ (page - 1) * limit + scope.$index + 1 }}
          </template>
        </el-table-column>

        <el-table-column prop="sampleNo" label="样本编号" align="center"  width="180"/>
        <el-table-column prop="trValue" label="tr值" align="center"  width="180"/>
        <el-table-column prop="createDate" label="创建时间" align="center"  width="220"/>
      </el-table>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelUpload()" size="small" icon="el-icon-refresh-right">取 消</el-button>
        <el-button type="primary" icon="el-icon-check" @click="saveDataBatch()" size="small">确 定</el-button>
      </span>
    </el-dialog>



  </div>
</template>

<script>
import mixinViewModule from '@/mixins/view-module'
import api from '@/api/product/proTr'
import Cookies from 'js-cookie'
const defaultForm = {
  id: '',
  sampleNo: '',
  trValue: ''
}
export default {
    mixins: [mixinViewModule],
  data() {
    return {
		uploadUrl:"",
        mixinViewModuleOptions: {
          createdIsNeed: false,
          exportURL: '/product/protr/export'
        },
        dataForm: {
          
        },
      reDataDialogVisible:false,
      headerData:{},
      fileList:[],
      listLoading: true, // 数据是否正在加载
      total: 0, // 数据库中的总记录数
      page: 1, // 默认页码
      limit: 10, // 每页记录数
      searchObj: {}, // 查询表单对象
      reTrs:[],
      createTimes: [],
      list:[],
      dialogVisible: false,
      proTr: defaultForm,
      loading:false,
      trIds: [], // 用户的角色ID的列表
      fileTrs:[],
      multipleSelection:[],
      fullLoading:{}
    }
  },

  // 生命周期函数：内存准备完毕，页面尚未渲染
  created() {
    this.fetchData()

    // roleApi.findAll().then(response => {
    //   this.roleList = response.data;
    // })
  },

  // 生命周期函数：内存准备完毕，页面渲染成功
  mounted() {
  },

  methods: {
    cancelUpload(){
      this.reDataDialogVisible=false
      this.fileList=[]
    },
    // 批量删除
    batchRemove() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要删除的记录！')
        return
      }
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 点击确定，远程调用ajax
        // 遍历selection，将id取出放入id列表
        var idList = []
        this.multipleSelection.forEach(item => {
          idList.push(item.id)
        })
        // 调用api
        return api.batchRemove(idList)
      }).then((response) => {
        this.fetchData()
        this.$message.success("删除成功")
      })
    },
    handleSelectionChange(selection) {
      this.multipleSelection = selection
    },
    saveDataBatch(){
      
        api.saveDataBatch(this.fileTrs).then( res => {

          this.$message.success("文件上传成功")
          this.reDataDialogVisible=false
          this.fileList=[]
          this.fetchData(this.page)
        })
      

    },
	handleChange(file,fileList){
		
		this.uploadUrl=`${window.SITE_CONFIG['apiURL']}/product/protr/file`
		const list = file.name.split(".")
		const type = list[list.length-1]
		
		const isExcel = (type==='xls' || type==='xlsx');
		if (!isExcel) {
		  this.$message.error('上传文件类型只支持xls、xlsx');
		  this.fileList=[]
		}
	},
    
    uploadSuccess(response, file, fileList){
      
      if(response.code == 0){
        var proTrs = response.data.proTrs
        if(proTrs){
          this.reDataDialogVisible=true
          this.reTrs=proTrs
          this.fileTrs=response.data.fileTrs
          this.trIds=response.data.ids
        }else{
          this.$message.success(`文件上传成功！`);

          this.fetchData(this.page)
        }

      }else{
        this.$message.error(response.msg);
      }
      this.fullLoading.close()
      this.fileList=[]

    },
    uploadFaild(err, file, fileList){
      this.$message.error(`上传时遇到了不可预期的错误，请重新尝试提交`);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，请勿重复提交`);
    },
    submitUpload() {
		
	if(this.$refs.upload.uploadFiles.length==0){
		this.$message.error(`请选择一个文件`);
		return false
	}
      this.headerData.token=Cookies.get('token')
      this.$refs.upload.submit();
      this.reTrs=[]
      this.fullLoading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

    },
    // 当页码发生改变的时候
    changeSize(size) {
      console.log(size)
      this.limit = size
      this.fetchData(1)
    },
    searchData(){
      this.loading=true
      this.fetchData()
      this.loading=false
    },
    // 加载banner列表数据
    fetchData(page = 1) {
      this.listLoading=true

      this.page = page

      if(this.createTimes && this.createTimes.length ==2) {
        this.searchObj.createTimeBegin = this.createTimes[0]
        this.searchObj.createTimeEnd = this.createTimes[1]
      }
      this.searchObj.limit=this.limit
      this.searchObj.page=this.page
      api.getPageList(this.searchObj).then(
        response => {
          //this.list = response.data.list
          this.list = response.data.data.records
          this.total = parseInt(response.data.data.total)
          // 数据加载并绑定成功
          this.listLoading = false
        }
      )
    },

    

    // 根据id删除数据
    removeDataById(id) {
      // debugger
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => { // promise
        // 点击确定，远程调用ajax
        var idList = []
        idList.push(id)
        return api.batchRemove(idList)
      }).then((response) => {
        this.fetchData(this.page)
        this.$message.success(response.message || '删除成功')
      }).catch(() => {
         this.$message.info('出现异常，删除失败')
      })
    },

   

    // 新增
    saveData() {
      api.save(this.proTr).then(response => {
        this.$message.success('操作成功')
        this.dialogVisible = false
        this.fetchData(this.page)
      })
    }

  }
}
</script>
